package com.gulimall.product.exception;

import com.gulimall.common.core.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import static com.gulimall.common.enums.BizCodeEnum.UNKNOW_EXC;
import static com.gulimall.common.enums.BizCodeEnum.VALID_EXC;

@RestControllerAdvice(basePackages = "com.gulimall.product.controller")//指定要扫描的controller包
@Slf4j
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handlerValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题：{},异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,Object> map = new HashMap<>();
        result.getFieldErrors().forEach(error->{
            String field = error.getField();
            String defaultMessage = error.getDefaultMessage();
            map.put(field,defaultMessage);
        });
        return Result.fail(map,VALID_EXC.getCode(),VALID_EXC.getDesc());
    }

    @ExceptionHandler(value = Throwable.class)
    public Result handlerException(Throwable e){
        log.error("出现异常问题：{},异常类型为：{}",e.getMessage(),e.getClass());
        return Result.fail(UNKNOW_EXC.getCode(),UNKNOW_EXC.getDesc());
    }
}
